package com.itheima.health.service.impl;

import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.ReportDao;
import com.itheima.health.dao.SetmeaDao;

import com.itheima.health.service.ReportService;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private SetmeaDao setmeaDao;
    @Autowired
    private ReportDao reportDao;


    /**
     * 会员数量折线图
     *
     * @return
     */
    public Map<String, Object> getMemberReport() {
        Map<String, Object> data = new HashMap<>();
        List<String> months = new ArrayList<>();
        List<Integer> memberCount = new ArrayList<>();

        // 获取近一年的月份
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date month = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(month));
        }

        // 查询每个月的会员数量
        for (String month : months) {
            String startDate = month + "-01";
            String endDate = month + "-31";
            int count = memberDao.getMemberCountByDate(startDate, endDate);
            memberCount.add(count);
        }

        data.put("months", months);
        data.put("memberCount", memberCount);

        return data;
    }

    /**
     * 套餐预约占比饼形图
     *
     * @return
     */
    public Map<String, Object> getSetmealReport() {
        Map<String, Object> data = new HashMap<>();
        List<String> setmealNames = new ArrayList<>();
        List<Map<String, Object>> setmealCount = new ArrayList<>();

        // 调用DAO层获取套餐数据
        List<Map<String, Object>> setmealData = setmeaDao.getSetmealReport();

        for (Map<String, Object> setmeal : setmealData) {
            String name = (String) setmeal.get("name");
            Long count = (Long) setmeal.get("count");

            setmealNames.add(name);

            Map<String, Object> countData = new HashMap<>();
            countData.put("name", name);
            countData.put("value", count);

            setmealCount.add(countData);
        }

        data.put("setmealNames", setmealNames);
        data.put("setmealCount", setmealCount);

        return data;
    }

    /**
     * 统计分析运营表
     * @return
     */
    public Map<String, Object> getBusinessReportData() {
        Map<String, Object> data = new HashMap<>();

        // 调用DAO层获取运营统计数据
        Integer todayVisitsNumber = reportDao.getTodayVisitsNumber();
        String reportDate = reportDao.getReportDate();
        Integer todayNewMember = reportDao.getTodayNewMember();
        Integer thisWeekVisitsNumber = reportDao.getThisWeekVisitsNumber();
        List<Map<String, Object>> hotSetmeal = reportDao.getHotSetmeal();
        Integer thisMonthNewMember = reportDao.getThisMonthNewMember();
        Integer thisWeekNewMember = reportDao.getThisWeekNewMember();
        Integer totalMember = reportDao.getTotalMember();
        Integer thisMonthOrderNumber = reportDao.getThisMonthOrderNumber();
        Integer thisMonthVisitsNumber = reportDao.getThisMonthVisitsNumber();
        Integer todayOrderNumber = reportDao.getTodayOrderNumber();
        Integer thisWeekOrderNumber = reportDao.getThisWeekOrderNumber();

        data.put("todayVisitsNumber", todayVisitsNumber);
        data.put("reportDate", reportDate);
        data.put("todayNewMember", todayNewMember);
        data.put("thisWeekVisitsNumber", thisWeekVisitsNumber);
        data.put("hotSetmeal", hotSetmeal);
        data.put("thisMonthNewMember", thisMonthNewMember);
        data.put("thisWeekNewMember", thisWeekNewMember);
        data.put("totalMember", totalMember);
        data.put("thisMonthOrderNumber", thisMonthOrderNumber);
        data.put("thisMonthVisitsNumber", thisMonthVisitsNumber);
        data.put("todayOrderNumber", todayOrderNumber);
        data.put("thisWeekOrderNumber", thisWeekOrderNumber);

        return data;
    }

    /**
     * 导出运营数据成Excel表格
     * @param response
     * @param result
     */
    public void exportBusinessReport(HttpServletResponse response, Map<String, Object> result) {
        try {

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/report_template.xlsx");
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            Integer rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

}
